//
//  NewConversationVC.m
//  SelfDriving
//  发起对话
//  Created by apple on 16/2/5.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "NewConversationVC.h"
#import "MsgCell.h"
#import "BusinessService+FJ.h"
#import "BusinessService+User.h"
#import "GroupListVC.h"
#import "GroupChatVC.h"
#import "FriendDetailsMainVC.h"
#import "UIImage+wiRoundedRectImage.h"
#import "XhwWebViewController.h"
@interface NewConversationVC ()<UITableViewDelegate,UITableViewDataSource,BaseTableDetelage,TCResultGroupDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UIView *topView;//228
@property (weak, nonatomic) IBOutlet UITextField *suosouField;
@property (weak, nonatomic) IBOutlet BaseTable *table;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *submitBtn;
@property (weak, nonatomic) IBOutlet UIView *dataView;

@end

@implementation NewConversationVC{
    UIView *topview;
    NSMutableArray *sdata;
    NSMutableArray *data;
    NSMutableArray *rdata;
    NSMutableArray *olddata;


}
-(void)viewWillAppear:(BOOL)animated{
    if ([AppDelegate shareDelegate].xzr) {
        CGRect r = _table.frame;
        r.origin.y = 0;
        _table.frame = r;
        
        CGRect t = _topView.frame;
        t.origin.y = 0;
        _topView.frame = t;
        [AppDelegate shareDelegate].xzr = NO;
    }
    //xhw2018-1-19改bug15267
    [self initData:1];
    //xhw2018-2-5加:
    CGRect xhw = _table.frame;
    xhw.size.height = xhw.size.height - _dataView.frame.size.height;
    _table.frame = xhw;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    topview = _topView;
    data = [[NSMutableArray alloc]init];
    _suosouField.layer.cornerRadius = 13;
    _table.bdelegate = self;
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 5)];
    _suosouField.leftView = view;
    _suosouField.leftViewMode = UITextFieldViewModeAlways;

    
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [btn addTarget:self action:@selector(qryAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setBackgroundImage:[UIImage imageNamed:@"fwss1"] forState:UIControlStateNormal];
    _suosouField.rightView = btn;
    _suosouField.rightViewMode = UITextFieldViewModeAlways;
    
    
}
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
    if(proposedNewLength==0){
        data = olddata;
        [_table reloadData];
    }
    return YES;
}

-(void)qryAction:(UIButton *)btn{
        NSMutableArray *rary = [[NSMutableArray alloc]init];
        if([_suosouField.text trim].length!=0){
            for (int i=0; i<_suosouField.text.length; i++) {
                NSRange range = NSMakeRange(i,1);
                NSString *subString = [_suosouField.text substringWithRange:range];
                const char *cString = [subString UTF8String];
                if (strlen(cString) == 3 )
                {
                    NSMutableArray *ary = rdata;
                    for (int i=0; i<ary.count;i++) {
                        LoginResponseModel *model = [[LoginResponseModel alloc]init];
                        [model serializationWithDictionary:[ary objectAtIndex:i]];
                        if([model.nickname rangeOfString:_suosouField.text].location !=NSNotFound)//_roaldSearchText
                        {
                            [rary addObject:model];
                        }
                    }
                }else if(strlen(cString)==1)
                {
                    for (int i =0; i<rdata.count; i++) {
                        LoginResponseModel *g = [[LoginResponseModel alloc]init];
                        [g serializationWithDictionary:[data objectAtIndex:i]];
                        NSString *n = [ValidateHelper firstCharactor:g.nickname];
                        if ([n isEqualToString:_suosouField.text.uppercaseString]) {
                            [rary addObject:g];
                        }
                    }
                }
            }
        }
    data =  [ValidateHelper dataFrom:rary];
    [_table reloadData];

}
-(void)initData:(int)index{
    sdata = [[NSMutableArray alloc]init];
    rdata = [[NSMutableArray alloc]init];
    olddata = [[NSMutableArray alloc]init];
    if (_type) {
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:_sessionid forKey:@"sessionid"];
        [[BusinessService shareInstance]contactList:dic success:^(id result) {
            data = [_table result:result olddata:data index:index];
            rdata = data;
            data =  [ValidateHelper dataFrom:data];
            olddata = data;
            [_table reloadData];
        } failure:^(id result) {
            [SVProgressHUD showErrorWithStatus:result];
        }];
    }else{
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        [dic setObject:[NSNumber numberWithInt:index] forKey:@"page"];
        [SVProgressHUD showWithStatus:@"加载中..."];
        [[BusinessService shareInstance]friendlist:dic success:^(id result) {
            [SVProgressHUD dismiss];
            NSMutableArray *ary = result;
            LoginResponseModel *users = [ary firstObject];
            NSMutableArray *sdtal = [[NSMutableArray alloc]init];
            for (NSMutableDictionary *user in users.friendlist) {
                if ([[user objectForKey:@"uid"] intValue] == [[AppDelegate shareDelegate].user.uid intValue]) {
                    continue;
                }
                [sdtal addObject:user];
            }
            data = [_table result:sdtal olddata:data index:index];
            rdata = data;
             data =  [ValidateHelper dataFrom:data];
            olddata = data;
            [_table reloadData];
        } failure:^(id result) {[SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:result];
        }];
    }
    
}
#pragma mark - 数据源方法
#pragma mark 返回分组数
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSLog(@"计算分组数");
    return data.count;
}

#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    KCContactGroup *group1 = data[section];
    return group1.contacts.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        if(_webtype){
            return 90;
        }
        return 50;
    }
    return 30;
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if(section == 0){
        topview = _topView;
        if(_webtype){
            BaseButton *btn = [[BaseButton alloc]initWithFrame:CGRectMake(0, 50, SCRE_WIDTH, 40)];
            [btn setTitle:@"选择一个群" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            btn.titleLabel.font = [ UIFont systemFontOfSize:14];
            btn.backgroundColor = [UIColor whiteColor];
            [btn addTarget:self action:@selector(togroupList:) forControlEvents:UIControlEventTouchUpInside];
            [topview addSubview:btn];
            CGRect r =  topview.frame;
            r.size.height = 90;
            topview.frame = r;
        }
        return topview;
    }
    return nil;
}
-(void)togroupList:(UIButton *)btn{
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    GroupListVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"GroupListVC"];
    searchResultDetailController.type = @"1";
    searchResultDetailController.content = _content;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
    
    
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}
#pragma mark返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    KCContactGroup *group=data[indexPath.section];
    LoginResponseModel *contact = group.contacts[indexPath.row];
    MsgCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MsgCell"];
    cell.img.layer.cornerRadius = cell.img.frame.size.width/2;
    cell.img.clipsToBounds = YES;
    cell.name.text = contact.nickname;
    [ValidateHelper setImage:contact.headsmall img:cell.img istoux:YES];
    cell.content.text = contact.sign;
    
    
    for (UIView *view in  [cell.selectView subviews]) {
        [view removeFromSuperview];
    }
    
    BaseButton *btn =[[BaseButton alloc]initWithFrame:CGRectMake(0, 60/2-cell.selectView.frame.size.height/2,cell.selectView.frame.size.width, cell.selectView.frame.size.height)];
    [btn setImage:[UIImage imageNamed:@"fqhh_d"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"fqhh_s"] forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(selectAction:) forControlEvents:UIControlEventTouchUpInside];
    
    btn.tag = indexPath.row+1;
    btn.model = contact;
    [cell.selectView addSubview:btn];
    for (int i = 0; i<sdata.count; i++) {
        LoginResponseModel *model = [sdata objectAtIndex:i];
        NSString *n1 = contact.nickname;
        NSString *n2 = model.nickname;
        if ([n1 isEqualToString:n2]) {
            btn.selected = YES;
        }
    }
    
    return cell;
}
#pragma mark 返回每组头标题名称
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if(section != 0){
        KCContactGroup *group=data[section];
        //        [SVProgressHUD showImage:[UIImage imageNamed:@""] status:group.name];
        return group.name;
    }
    return nil;
}

#pragma mark 返回每组标题索引
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    NSMutableArray *indexs=[[NSMutableArray alloc]init];
    for(KCContactGroup *group in data){
        [indexs addObject:group.name];
    }
    return indexs;
}

-(void)selectAction:(BaseButton *)btn{
    btn.selected = !btn.selected;
    if (btn.selected) {
        [sdata addObject:btn.model];
    }else{
        [sdata removeObject:btn.model];
    }
    int n = (int)sdata.count;
    if (n==0) {
        [_submitBtn setTitle:[NSString stringWithFormat:@"确定"]];
    }else{
        [_submitBtn setTitle:[NSString stringWithFormat:@"确定(%d)",n]];
    }
    while ([_dataView.subviews lastObject] != nil) {
        [(UIView*)[_dataView.subviews lastObject] removeFromSuperview];
    }
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCRE_WIDTH, 40)];
    [_dataView addSubview:scrollView];
    int h = 5;
    for (int i = 0;i<sdata.count; i++) {
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(h, 0, 35, 35)];
        h = h + 45;
        LoginResponseModel *user = [sdata objectAtIndex:i];
        [ValidateHelper setImage:user.headsmall img:img istoux:YES];
        [scrollView addSubview:img];
    }
    scrollView.contentSize = CGSizeMake(h+35, 0);
    [_table reloadData];
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    KCContactGroup *group = data[indexPath.section];
    LoginResponseModel *contact = group.contacts[indexPath.row];
    DTModel *model = [[DTModel alloc]init];
    model.uid = contact.uid;
    [AppDelegate shareDelegate].xzr = YES;
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                 bundle:[NSBundle mainBundle]];
    FriendDetailsMainVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"FriendDetailsMainVC"];
    searchResultDetailController.model = model;
    [self.navigationController pushViewController:searchResultDetailController animated:YES];
}
- (IBAction)backAction:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma 确定，然后跳转至群聊界面
- (IBAction)qunliaoAction:(UIBarButtonItem *)sender {
    if (_webtype) {//web分享内容选择发送到好友
        for (int  i = 0; i<sdata.count; i++) {
            LoginResponseModel *model = [sdata objectAtIndex:i];
            TCMessage* msg = [TCMessage newMessage];
            msg.typeChat = 100;
            msg.typeFile = 1;
            msg.from.name = [AppDelegate shareDelegate].user.nickname;
            msg.from.ID = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
            msg.from.head = [AppDelegate shareDelegate].user.headsmall;
            msg.to.ID =[NSString stringWithFormat:@"%@",model.uid];
            msg.to.name = model.nickname;
            msg.to.head = model.headsmall;
            
            msg.typeFile = 1;
            msg.state = forMessageStateHavent;
            msg.body = [[TCTextMessageBody alloc] init];
            msg.bodyText.content = _content;
            [[AppDelegate shareDelegate]sendMessage:msg];
        }
        UINavigationController *navigationVC = self.navigationController;
        NSMutableArray *viewControllers = [[NSMutableArray alloc] init];
        //    遍历导航控制器中的控制器
        for (UIViewController *vc in navigationVC.viewControllers) {
            [viewControllers addObject:vc];
            if ([vc isKindOfClass:[XhwWebViewController class]]) {
                break;
            }
        }
        //    把控制器重新添加到导航控制器
        [navigationVC setViewControllers:viewControllers animated:YES];
    }else{
        NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
        NSMutableString *str = [[NSMutableString alloc]init];
        NSMutableString *uid = [[NSMutableString alloc]initWithFormat:@"%@,",[AppDelegate shareDelegate].user.uid];
        NSMutableArray *uidary = [[NSMutableArray alloc]init];
         NSMutableString *struids = [[NSMutableString alloc]init];
        for (int  i = 0; i<sdata.count; i++) {
            LoginResponseModel *model = [sdata objectAtIndex:i];
            [str appendFormat:@"%@,",model.nickname];
            [uid appendFormat:@"%@,",model.uid];
            [uidary addObject:model.uid];
            [struids appendFormat:@"%@,",model.uid];
        }
        if (_type) {
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
            [dic setObject:struids forKey:@"uids"];
            [dic setObject:_sessionid forKey:@"sessionid"];
            [[BusinessService shareInstance]addUserToSession:dic success:^(id result) {
                [self.navigationController popViewControllerAnimated:YES];
                return ;
            } failure:^(id result) {
                [SVProgressHUD showErrorWithStatus:result];
            }];
            return;
        }
        
        [SVProgressHUD showWithStatus:@"创建中..."];
        [sdata addObject:[AppDelegate shareDelegate].user];
        [[ThinkChat instance]createConversationName:str userList:uidary delegate:self];
    }
}
- (void)tcResultGroup:(TCGroup *)itemG error:(TCError *)itemE {
    [SVProgressHUD dismiss];
    if (itemE == nil&&itemG.ID!=nil) {
        [SVProgressHUD showSuccessWithStatus:@"创建成功"];
        UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"MS"
                                                                     bundle:[NSBundle mainBundle]];
        GroupChatVC *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"GroupChatVC"];
        searchResultDetailController.model = itemG;
        [self.navigationController pushViewController:searchResultDetailController animated:YES];
    } else {
        [sdata removeObject:[AppDelegate shareDelegate].user];
        [SVProgressHUD showErrorWithStatus:@"创建失败"];
    }
}


@end
